<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="添加商品信息" type="info" 
      :closable="false"  
      show-icon
      center
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeStepIndex" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>

      <el-form :model="goodsForm" :rules="goodsFormRules" ref="goodsFormRef" label-width="120px">
        <el-tabs tab-position="left" v-model="activeTabName" :before-leave="handleTabLeave">
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name" required >
              <el-input v-model="goodsForm.goods_name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goods_price" required>
              <el-input v-model="goodsForm.goods_price" ></el-input>
            </el-form-item>
            <el-form-item label="商品重量(克)" prop="goods_weight" required>
              <el-input v-model="goodsForm.goods_weight" ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" required>
              <el-input-number v-model="goodsForm.goods_number" :min="1" :step="1"></el-input-number>
            </el-form-item>
            <el-form-item label="商品分类" required>
              <el-cascader 
                :options="categoryList"
                :props="cascaderProps"
                v-model="selectedCateIds"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <div  v-for="attr in manyAttrs" :key="attr.attr_id">
              <p>{{attr.attr_name}}</p>
              <el-checkbox-group v-model="attr.checkedValArr" @change="isManyUpdated=true">
                <el-checkbox v-for="val in attr.attrValArr" :label="val" :key="val">
                  {{val}}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <div  v-for="attr in onlyAttrs" :key="attr.attr_id">
              <p>{{attr.attr_name}}</p>
              <el-checkbox-group v-model="attr.checkedValArr" @change="isOnlyUpdated=true">
                <el-checkbox v-for="val in attr.attrValArr" :label="val" :key="val">
                  {{val}}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <file-upload 
              :supportFormats='["image/png","image/jpg","image/jpeg"]'
              :maxSize="1"
              :successImageSrc="goodsImgSrc"
              uploadTip="支持图片格式.jpg .png .jpeg"
              @uploadFile="uploadGoodsImg"
            ></file-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容" >
            <quill-editor
              ref="quillEditorRef"
              v-model="goodsForm.goods_introduce"
            />
            <div class="submitBtnWrap">
              <el-button class="submitBtn" type="primary"
                @click="handleGoodsAdd"
              >完成, 提交商品</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
  
</template>
<script>
import FileUpload from '../../../components/FileUpload'
import { getCategories } from '../../../api/cates'
import { getAttributesByCateId } from '../../../api/params'
import {addGoods} from '../../../api/goods'
import {checkNumber, checkInteger} from '../../../utils/validate'
import {splitBy} from '../../../utils/util'
import {uploadImg} from '../../../api/upload'

export default {
  components:{
    'file-upload':FileUpload,
  },
  created(){
    this.getCategoryList()
  },
  data(){
    return {
      activeTabName:'0',
      categoryList:[],
      // 级联选择的配置
      cascaderProps:{
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 分类
      selectedCateIds:[],
      // 商品表单
      goodsForm:{
        goods_name:'',
        goods_cat:'',
        goods_price:0,
        goods_number:0,
        goods_weight:0,
        goods_introduce:'',
        pics:[],
        attrs:[]
      },
      goodsFormRules:{
        goods_name:[{
          required:true, trigger:'blur',  message: '商品名称不能为空',
        }],
        goods_price:{validator:checkNumber,trigger:'blur', fname:'商品价格'},
        goods_weight:{validator:checkNumber,trigger:'blur', fname:'商品重量'},
        goods_number:{validator:checkInteger, trigger:'blur',fname:'商品数量'}
      },
      // 参数
      manyAttrs:[],
      isManyUpdated:true,
      // 属性
      onlyAttrs:[],
      isOnlyUpdated:true,
      // 商品图片地址
      goodsImgSrc:''
    }
  },
  computed:{
    activeStepIndex(){
      return this.activeTabName - 0
    }
  },
  methods:{
    //处理标签页切换
    async handleTabLeave(activeName, oldActiveName){
      const index = parseInt(activeName)
      const oldIndex = parseInt(oldActiveName)
      if(index - oldIndex > 1){
        this.$message({
          type:'warning',
          message:'请完成前面的步骤！'
        })
        throw new Error('请完成前面的步骤！')
      }
      // 步骤向后进行
      if(index > oldIndex){
        try {
          switch(index){
            case 1:{ //商品参数页
            // 验证字段
              await this.validatePartForm([
                  'goods_name','goods_price','goods_weight','goods_number'
              ])
              // console.log(this.selectedCateIds);
              if(!this.selectedCateIds.length){
                throw new Error('请选择商品分类！')
              }
              //设置分类
              this.goodsForm.goods_cat = this.selectedCateIds.join(',')
              //获取商品参数
              if(!this.manyAttrs.length){
                this.manyAttrs = await this.getAttributes(this.selectedCateIds[this.selectedCateIds.length-1], 'many')
              }
            }
            break
            case 2:{ //商品属性页
              // 封装商品参数
              if(this.isManyUpdated){
                this.goodsForm.attrs = this.formatAttrs(this.manyAttrs)
                this.isManyUpdated = false
              }
              // 获取商品属性
              if(!this.onlyAttrs.length){
                this.onlyAttrs = await this.getAttributes(this.selectedCateIds[this.selectedCateIds.length-1], 'only')
              }
              
            }
            break
            case 3:{ //商品图片页
              // 封装商品属性
              if(this.isOnlyUpdated){
                  //对manyAttrs重新处理，是为了避免返回上一步骤修改导致出错
                const manyArr = this.formatAttrs(this.manyAttrs) 
                const onlyArr = this.formatAttrs(this.onlyAttrs)
                this.goodsForm.attrs = manyArr.concat(onlyArr)
                this.isOnlyUpdated = false
              }
              
            }
            break
          }
        } catch (err) {
          let errMsg = null
          if(typeof err === 'string'){
            errMsg = err
          }else{
            errMsg = err.message
          }
          this.$message({
              type:'warning',
              message:errMsg
            })
          throw new Error('表单部分验证不通过！')
        }
      }
    },
    // 验证部分字段
    validatePartForm(fields){
      let fCount = 0
      return new Promise((resolve,reject)=>{
        this.$refs.goodsFormRef.validateField(fields,errMsg=>{
          fCount++
          if(errMsg){
            reject(errMsg)
          }else{
            if(fields.length===fCount) //不是最后一个字段不返回成功，到最后一个时才成功
              resolve('通过验证')
          }
        })
      })
    },
    // 获取分类
    async getCategoryList(){
      try {
        const res = await getCategories()
        this.categoryList = res.data
      } catch (err) {
        console.log(err);
      }
    },
    // 获取商品参数
    async getAttributes(id,type){
      try {
        const res = await getAttributesByCateId(id,{
          sel:type
        })
        const attrs = res.data
        attrs.forEach(item=>{
                item.attrValArr = splitBy(item.attr_vals,' ')
                item.checkedValArr = item.attrValArr
              })
        return attrs
      } catch (err) {
        console.log(err);
      }
    },
    // 封装attrs
    formatAttrs(attrs){
      return attrs.map((item,index)=>{
        return {
          attr_id:item.attr_id,
          attr_value: item.checkedValArr.join(' ')
        }
      })
    },
    // 上传商品图片
    async uploadGoodsImg(file){
      // console.log(file);
      try {
        let formData = new FormData()
        formData.append('file',file)
        const res = await uploadImg(formData)
        // console.log(res);
        this.goodsImgSrc = res.data.url
        // 这里写成只传1张图片，另外这个pics不是空数组貌似服务端会报错500
        // this.goodsForm.pics = [{
        //   'pic':res.data.tmp_path
        // }]
        this.$message({
          type:'success',
          message:res.meta.msg
        })
      } catch (err) {
        console.log(err);
      } 
    },
    // 提交添加的商品
    async handleGoodsAdd(){
      try {
        const res = await addGoods(this.goodsForm)
        this.$message({
          type:'success',
          message:res.meta.msg
        })
        //跳转路由
        this.$router.back()
      } catch (err) {
        console.log(err);
      }
    }
  }
}
</script>
<style scoped>
.el-steps{
  margin: 10px 0 20px;
}

.quill-editor >>> .ql-editor{
  height: 300px;
}

.submitBtnWrap{
  text-align: center;
}
.submitBtnWrap .submitBtn{
  margin: 20px 0;
}
</style>